package com.shengchang.hu.supervision.UI;

import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.DialogInterface;
import android.content.Intent;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.MifareClassic;
import android.nfc.tech.MifareUltralight;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Parcelable;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.shengchang.hu.supervision.R;
import com.shengchang.hu.supervision.ToolBar.InBoundBar;
import com.shengchang.hu.supervision.Utils.Contants;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.nio.charset.Charset;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.InputMismatchException;
import java.util.List;
import java.util.Locale;

import NFC.NdefMessageParser;
import NFC.ParsedNdefRecord;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class ExtramuralActivity extends BaseActivity {

    InBoundBar checkedbar;
    private static final DateFormat TIME_FORMAT = SimpleDateFormat
            .getDateTimeInstance();
    private NfcAdapter mAdapter;
    private PendingIntent mPendingIntent;
    private NdefMessage mNdefPushMessage;
    private AlertDialog mDialog;
    private String departmentname;
    private String departmentid;
    private static final String Terminal_getAgencyInformation = Contants.Terminal_getAgencyInformation;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_extramural);
        checkedbar=findViewById(R.id.checkedbar);
        checkedbar.setLeftTitleClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        resolveIntent(getIntent());
        mDialog = new AlertDialog.Builder(this).setNeutralButton("Ok", null)
                .create();

        // 获取默认的NFC控制器
        mAdapter = NfcAdapter.getDefaultAdapter(this);

        //拦截系统级的NFC扫描，例如扫描蓝牙
        mPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this,
                getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
        mNdefPushMessage = new NdefMessage(new NdefRecord[] { newTextRecord("",
                Locale.ENGLISH, true) });
    }
    @Override
    protected void onResume() {
        super.onResume();
        if (mAdapter == null) {
            if (!mAdapter.isEnabled()) {
                showWirelessSettingsDialog();
            }

            showMessage("error", " NO NFC");
            showShortToast("设备不支持NFC");


            return;
        }
        if (!mAdapter.isEnabled()) {
            showShortToast("请在系统设置中先启用NFC功能");

            return;
        }

        if (mAdapter != null) {
            //隐式启动
            mAdapter.enableForegroundDispatch(this, mPendingIntent, null, null);
            mAdapter.enableForegroundNdefPush(this, mNdefPushMessage);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mAdapter != null) {
            //隐式启动
            mAdapter.disableForegroundDispatch(this);
            mAdapter.disableForegroundNdefPush(this);
        }
    }

    private void showMessage(String title, String message) {
        mDialog.setTitle(title);
        mDialog.setMessage(message);
        mDialog.show();
    }

    private NdefRecord newTextRecord(String text, Locale locale,
                                     boolean encodeInUtf8) {
        byte[] langBytes = locale.getLanguage().getBytes(
                Charset.forName("US-ASCII"));

        Charset utfEncoding = encodeInUtf8 ? Charset.forName("UTF-8") : Charset
                .forName("UTF-16");
        byte[] textBytes = text.getBytes(utfEncoding);

        int utfBit = encodeInUtf8 ? 0 : (1 << 7);
        char status = (char) (utfBit + langBytes.length);

        byte[] data = new byte[1 + langBytes.length + textBytes.length];
        data[0] = (byte) status;
        System.arraycopy(langBytes, 0, data, 1, langBytes.length);
        System.arraycopy(textBytes, 0, data, 1 + langBytes.length,
                textBytes.length);

        return new NdefRecord(NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_TEXT,
                new byte[0], data);
    }

    private void showWirelessSettingsDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("nfc_disabled");
        builder.setPositiveButton(android.R.string.ok,
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialogInterface, int i) {
                        Intent intent = new Intent(
                                Settings.ACTION_WIRELESS_SETTINGS);
                        startActivity(intent);
                    }
                });
        builder.setNegativeButton(android.R.string.cancel,
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialogInterface, int i) {
                        finish();
                    }
                });
        builder.create().show();
        return;
    }

    //    private void initUHF() {
//        SharedPreferences sharedPortPath = getSharedPreferences("portPath", 0);
//
//        serialPortPath = sharedPortPath.getString("portPath", "/dev/ttyMT2");
//
//        mCommonApi = new CommonApi();
//        openGPIO();
//
//
//        mComFd = mCommonApi.openCom(serialPortPath, 115200, 8, 'N', 1);
//
//        new Handler().postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                // TODO Auto-generated method stub
//                mCommonApi.setGpioDir(53, 1);
//                int ret = mCommonApi.setGpioOut(53, 1);
//                mCommonApi.setGpioDir(78, 1);
//                int ret1 = mCommonApi.setGpioOut(78, 1);
//                if (ret == 0) {
////                    Toast.makeText(CheckedActivity.this, "读卡成功" , Toast.LENGTH_SHORT).show();
//                } else {
//                    Toast.makeText(CheckedActivity.this, "卡外信息出错", Toast.LENGTH_SHORT).show();
//                }
//            }
//        }, 500);
//
//        UhfReader.setPortPath(serialPortPath);
//        reader = UhfReader.getInstance();
//
//        readerDevice = UhfReaderDevice.getInstance();
//        if (reader == null) {
//            showTipDialog("卡片读取失败");
//
//            return;
//        }
//        if (readerDevice == null) {
//
//            showTipDialog("校验卡读取失败");
//
//        }
//        try {
//            Thread.sleep(100);
//        } catch (InterruptedException e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        }
//
//        SharedPreferences shared = getSharedPreferences("power", 0);
//        int value = shared.getInt("value", 26);
//        Log.d("", "value" + value);
//        reader.setOutputPower(value);
//
//        powerOn = true;
//
//
//        // TODO Auto-generated method stub
//        if (!powerOn) {
//
//            powerOn = true;
//            readerDevice.powerOn();
//
//            Toast.makeText(getApplicationContext(), "power On", Toast.LENGTH_LONG).show();
//
//        }
//
//        Thread thread = new InventoryThread();
//        thread.start();
//
//        Util.initSoundPool(this);
//        if (!startFlag) {
//            startFlag = true;
//
//        }
//        byte[] versionBytes = reader.getFirmware();
//        if (versionBytes != null) {
////				reader.setWorkArea(3);
//            Util.play(1, 0);
//            String version = new String(versionBytes);
//
//
//        }
//
//
//    }
//
//    //rfid卡读取成功之后的网络请求操作和输入框的赋值
//    class InventoryThread extends Thread {
//        private List<byte[]> epcList;
//
//        @Override
//        public void run() {
//            super.run();
//            while (runFlag) {
//                if (startFlag) {
////					reader.stopInventoryMulti()
//                    epcList = reader.inventoryRealTime(); //
//                    if (epcList != null && !epcList.isEmpty()) {
//                        Util.play(1, 0);
//                        for (byte[] epc : epcList) {
//                            if (epc != null) {
//
//                                final String epcStr = Tools.Bytes2HexString(epc, epc.length);
//                                Uhfdata = epcStr;
//
//                                if (!TextUtils.isEmpty(Uhfdata)) {
//
//
//
//                                    Log.d("dueha", epcStr);
//                                } else {
//                                    showShortToast("刷卡失败");
//                                }
//
//                                Log.d("ueiqojs", epcStr);
//                                if (!Uhfdata.equals("") || Uhfdata != null) {
//
//                                    if (readerDevice != null) {
//                                        readerDevice.powerOff();
//                                    }
//                                    if (mComFd > 0) {
//                                        mCommonApi.setGpioDir(78, 1);
//                                        mCommonApi.setGpioOut(78, 0);
//
//                                        mCommonApi.setGpioDir(83, 1);
//                                        mCommonApi.setGpioOut(83, 0);
//                                        mCommonApi.closeCom(mComFd);
//                                    }
////
//                                }
//
//
//                            }
//                        }
//                    }
//                    epcList = null;
//                    try {
//                        Thread.sleep(40);
//                    } catch (InterruptedException e) {
//                        // TODO Auto-generated catch block
//                        e.printStackTrace();
//                    }
//                }
//            }
//        }
//    }
//初步判断是什么类型NFC卡
    private void resolveIntent(Intent intent) {
        String action = intent.getAction();
        if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)
                || NfcAdapter.ACTION_TECH_DISCOVERED.equals(action)
                || NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) {
            Parcelable[] rawMsgs = intent
                    .getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
            NdefMessage[] msgs;
            if (rawMsgs != null) {
                msgs = new NdefMessage[rawMsgs.length];
                for (int i = 0; i < rawMsgs.length; i++) {
                    msgs[i] = (NdefMessage) rawMsgs[i];
                }
            } else {
                // Unknown tag type
                byte[] empty = new byte[0];
                byte[] id = intent.getByteArrayExtra(NfcAdapter.EXTRA_ID);
                Parcelable tag = intent
                        .getParcelableExtra(NfcAdapter.EXTRA_TAG);
                byte[] payload = dumpTagData(tag).getBytes();
                NdefRecord record = new NdefRecord(NdefRecord.TNF_UNKNOWN,
                        empty, id, payload);
                NdefMessage msg = new NdefMessage(new NdefRecord[] { record });
                msgs = new NdefMessage[] { msg };
            }
            // Setup the views

//        showShortToast("");
            buildTagViews(msgs);
        }
    }

    //一般公家卡，扫描的信息
    private String dumpTagData(Parcelable p) {
        StringBuilder sb = new StringBuilder();
        Tag tag = (Tag) p;
        byte[] id = tag.getId();
        sb.append("Tag ID (hex): ").append(getHex(id)).append("\n");
        sb.append("Tag ID (dec): ").append(getDec(id)).append("\n");
        sb.append("ID (reversed): ").append(getReversed(id)).append("\n");

        String prefix = "android.nfc.tech.";
        sb.append("Technologies: ");
        for (String tech : tag.getTechList()) {
            sb.append(tech.substring(prefix.length()));
            sb.append(", ");
        }
        sb.delete(sb.length() - 2, sb.length());
        for (String tech : tag.getTechList()) {
            if (tech.equals(MifareClassic.class.getName())) {
                sb.append('\n');
                MifareClassic mifareTag = MifareClassic.get(tag);
                String type = "Unknown";
                switch (mifareTag.getType()) {
                    case MifareClassic.TYPE_CLASSIC:
                        type = "Classic";
                        break;
                    case MifareClassic.TYPE_PLUS:
                        type = "Plus";
                        break;
                    case MifareClassic.TYPE_PRO:
                        type = "Pro";
                        break;
                }
                sb.append("Mifare Classic type: ");
                sb.append(type);
                sb.append('\n');

                sb.append("Mifare size: ");
                sb.append(mifareTag.getSize() + " bytes");
                sb.append('\n');

                sb.append("Mifare sectors: ");
                sb.append(mifareTag.getSectorCount());
                sb.append('\n');

                sb.append("Mifare blocks: ");
                sb.append(mifareTag.getBlockCount());
            }

            if (tech.equals(MifareUltralight.class.getName())) {
                sb.append('\n');
                MifareUltralight mifareUlTag = MifareUltralight.get(tag);
                String type = "Unknown";
                switch (mifareUlTag.getType()) {
                    case MifareUltralight.TYPE_ULTRALIGHT:
                        type = "Ultralight";
                        break;
                    case MifareUltralight.TYPE_ULTRALIGHT_C:
                        type = "Ultralight C";
                        break;
                }
                sb.append("Mifare Ultralight type: ");
                sb.append(type);
            }
        }

        return sb.toString();
    }

    private String getHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (int i = bytes.length - 1; i >= 0; --i) {
            int b = bytes[i] & 0xff;
            if (b < 0x10)
                sb.append('0');
            sb.append(Integer.toHexString(b));
            if (i > 0) {
                sb.append(" ");
            }
        }
        return sb.toString();
    }

    private long getDec(byte[] bytes) {
        long result = 0;
        long factor = 1;
        for (int i = 0; i < bytes.length; ++i) {
            long value = bytes[i] & 0xffl;
            result += value * factor;
            factor *= 256l;
        }
        return result;
    }

    private long getReversed(byte[] bytes) {
        long result = 0;
        long factor = 1;
        for (int i = bytes.length - 1; i >= 0; --i) {
            long value = bytes[i] & 0xffl;
            result += value * factor;
            factor *= 256l;
        }
        return result;
    }

    //16进制字符串转换为String
//    private String hexString = "0123456789ABCDEF";
//    public String decode(String bytes) {
//        if (bytes.length() != 30) {
//            return null;
//        }
//        ByteArrayOutputStream baos = new ByteArrayOutputStream(
//                bytes.length() / 2);
//        // 将每2位16进制整数组装成一个字节
//        for (int i = 0; i < bytes.length(); i += 2)
//            baos.write((hexString.indexOf(bytes.charAt(i)) << 4 | hexString
//                    .indexOf(bytes.charAt(i + 1))));
//        return new String(baos.toByteArray());
//    }
    //显示NFC扫描的数据
    private void buildTagViews(NdefMessage[] msgs) {
        if (msgs == null || msgs.length == 0) {
            return;
        }
        Date now = new Date();
        List<ParsedNdefRecord> records = NdefMessageParser.parse(msgs[0]);
        final int size = records.size();
        for (int i = 0; i < size; i++) {
            TextView timeView = new TextView(this);
            timeView.setText(TIME_FORMAT.format(now));
            ParsedNdefRecord record = records.get(i);

//            showShortToast(String.valueOf(record.getViewText()));
            String viewText = record.getViewText();
            String[] split = viewText.split("\\n");
            String[] split2 = split[1].split(" ");
            final String string = split2[3];
            if (!TextUtils.isEmpty(string)){
                new Thread(new Runnable() {
                    @Override
                    public void run() {

                        try {

                            if ( "0".equals(string.substring(0,1))){

                                final String substring = string.substring(1, string.length());
                                Handler handler = new Handler(Looper.getMainLooper());
                                handler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        showProgressDialog();
                                        CheckedRequest(substring);

                                    }
                                });
                            }else{
                                Handler handler = new Handler(Looper.getMainLooper());
                                handler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        showProgressDialog();
                                        CheckedRequest(string);

                                    }
                                });
                            }
                        } catch (InputMismatchException e) {
                            e.printStackTrace();
                        }

                    }
                }).start();
//               showShortToast(string);
//               Log.d("record", String.valueOf(record.getViewText()));
            }else{
                showShortToast("读卡失败");
            }

        }
    }

    //获取系统隐式启动的
    @Override
    public void onNewIntent(Intent intent) {
        setIntent(intent);
        resolveIntent(intent);
    }
    private void CheckedRequest(String uhfdata) {
        OkHttpClient moKhttp=new OkHttpClient();
        RequestBody formBody = new FormBody.Builder()
                .add("cardCode",uhfdata)
                .build();
        Request request = new Request.Builder()
                .url(Terminal_getAgencyInformation)
                .post(formBody)
                .build();
        Log.d("dsdsdsx",Terminal_getAgencyInformation+"?cardCode="+uhfdata);
        Call call = moKhttp.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Handler handler = new Handler(Looper.getMainLooper());
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                dismissProgressDialog();
                                // 放在UI线程弹Toast
                                showLongToast("请求失败，请确认网络");
                            }				});				//此处会发生异常//
                    }		}).start();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final   String  Departmentstr=response.body().string();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        DepartmentRequest(Departmentstr);
                    }
                });

            }
        });

    }

    private void DepartmentRequest(String departmentstr) {
        try {
            JSONObject Departmentjson=new JSONObject(departmentstr);
            String  DepartmentMsg=Departmentjson.getString("message");
            if (DepartmentMsg.equals("20004")){
                dismissProgressDialog();
                showShortToast("网络请求异常");
            }else if(DepartmentMsg.equals("20005")){
                dismissProgressDialog();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Handler handler = new Handler(Looper.getMainLooper());
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                Intent intent = new Intent(ExtramuralActivity.this, ExInBoundActivity.class);
                                intent.putExtra("Ufhdata", departmentname);
                                intent.putExtra("departmentid",departmentid);
                                startActivity(intent);
                                finish();
                            }
                        });				//此处会发生异常//
                    }		}).start();

            }else  if (DepartmentMsg.equals("20008")){
                dismissProgressDialog();
                showShortToast("查无此卡");
            } else if (DepartmentMsg.equals("20009")){
                dismissProgressDialog();
                showShortToast("类型不符合");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        try {
            JSONObject  mJson=new JSONObject(departmentstr);
            JSONObject jsonObject = mJson.getJSONObject("agency");
            departmentname=jsonObject.getString("agencyName");
            departmentid=jsonObject.getString("agencyId");
            Log.d("hdueiw",  departmentid);


        } catch (JSONException e) {
            e.printStackTrace();
        }

    }






    @Override
    protected void onStop() {
        super.onStop();



    }

    @Override
    protected void onDestroy() {
        super.onDestroy();


    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finish();
    }
}
